import React from 'react';
import PropTypes from 'prop-types';
import { Dialog } from '@teamix/ui';
import exceed from 'utils/apimap';
import ListLoading from 'atComponents/ListLoading';
import Detail from './detail';
import './index.scss';
import intl from '../../../../../../../../../../locale';

const prefix = 'prehook-history-dialog';
export default class GroupModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
    closeModal: () => {},
  };

  constructor(props) {
    super(props);

    this.state = {
      isModalOpen: false,
      isLoading: true,
      record: {},
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  componentDidMount() {
    this.getData(1);
  }

  // 获取敏感行为表
  getData = () => {
    const { testUrl } = this.props;
    const { pathResource } = window.FORCE;
    this.setState({
      isLoading: true,
    });

    exceed
      .fetch({
        api: 'project.repo.prehook.test',
        params: {
          projectId: pathResource.id,
          url: encodeURIComponent(testUrl),
        },
      })
      .then((result) => {
        this.setState({
          record: result,
          isLoading: false,
        });
      })
      .fail(() => {
        this.setState({
          isLoading: false,
        });
      });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal();
  };

  render() {
    const { record, isLoading } = this.state;
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            title={intl.get({
              id: 'code-assets.containers.historyModal.TestLink',
              defaultMessage: '测试链接',
            })}
            visible
            style={{ width: 800 }}
            onCancel={this.onClose}
            onClose={this.onClose}
            footer={false}
            className={prefix}
          >
            <div className={`${prefix}-container`}>
              {isLoading ? <ListLoading /> : <Detail record={record} />}
            </div>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
